<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/12/012
 * Time: 10:34
 */

namespace App\Http\Common\Lib;
/**
 * 图片压缩
 * Class ImgCompress
 * @package App\Http\Common\Lib
 */
class ImgCompress
{
	private $src;
	private $image;
	private $imageInfo;
	private $percent = 1;//压缩比例，原图比例1

	/**
	 * 图片压缩
	 * ImgCompress constructor.
	 * @param $src  图片地址
	 * @param int $percent 压缩比例
	 */
	public function __construct($src, $percent = 1)
	{
		$this->src = $src;
		$this->percent = $percent;
	}

	/**
	 * 图片压缩
	 * @param string $saveName 图片的保存名，不填写则直接显示图片
	 */
	public function compressImg($saveName = '')
	{
		$this->_openImage();
		if (!empty($saveName)) {
			return $this->_saveImage($saveName); //保存
		} else {
			$this->_showImage();
		}
	}

	/**
	 * 打开原图
	 */
	private function _openImage()
	{
		list($width, $height, $type, $attr) = getimagesize($this->src);
		$this->imageInfo = array(
			'width' => $width,
			'height' => $height,
			'type' => image_type_to_extension($type, false),
			'attr' => $attr,
		);
		$fun = "imagecreatefrom" . $this->imageInfo['type'];
		$this->image = $fun($this->src);
		$this->_thumpImage();
	}

	/**
	 * 生成压缩图
	 */
	private function _thumpImage()
	{
		$newWidth = $this->imageInfo['width'] * $this->percent;
		$newHeight = $this->imageInfo['height'] * $this->percent;
		$imageThump = imagecreatetruecolor($newWidth, $newHeight);
		//将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度
		imagecopyresampled($imageThump, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $this->imageInfo['width'], $this->imageInfo['height']);
		imagedestroy($this->image);
		$this->image = $imageThump;
	}

	/**
	 * 显示图片
	 */
	private function _showImage()
	{
		header('Content-Type: image/' . $this->imageInfo['type']);
		$funcs = "image" . $this->imageInfo['type'];
		$funcs($this->image);
	}

	/**
	 * 保存压缩图片
	 * @param $dstImgName
	 * @return bool
	 */
	private function _saveImage($dstImgName)
	{
		if (empty($dstImgName)) {
			return false;
		}
		$allowImgs = ['.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'];  //如果目标图片名有后缀就用目标图片扩展名 后缀，如果没有，则用源图的扩展名
		$dstExt = strrchr($dstImgName, ".");
		$sourseExt = strrchr($this->src, ".");
		if (!empty($dstExt)) {
			$dstExt = strtolower($dstExt);
		}
		if (!empty($sourseExt)) {
			$sourseExt = strtolower($sourseExt);
		}
		//有指定目标名扩展名
		if (!empty($dstExt) && in_array($dstExt, $allowImgs)) {
			$dstName = $dstImgName;
		} elseif (!empty($sourseExt) && in_array($sourseExt, $allowImgs)) {
			$dstName = $dstImgName . $sourseExt;
		} else {
			$dstName = $dstImgName . $this->imageInfo['type'];
		}

		$funcs = "image" . $this->imageInfo['type'];
		$res = $funcs($this->image, $dstName);
		return $res;
	}

	public function __destruct()
	{
		if ($this->image) {
			imagedestroy($this->image);
		}
	}
}